import {PageContainer} from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import React, {useEffect, useState, useRef} from "react";
import {Button, Input, Space, Table} from 'antd';
import {history, Link} from 'umi';
import axios from 'axios';
import {getDetailByID} from '@/services/doa/repo'
import ProTable from '@ant-design/pro-table';


import * as echarts from 'echarts/core';
import {
  TitleComponent,
  TooltipComponent,
  GeoComponent
} from 'echarts/components';
import {LinesChart} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';
import * as https from "https";

echarts.use([
  TitleComponent,
  TooltipComponent,
  GeoComponent,
  LinesChart,
  CanvasRenderer
]);


export default () => {


  let svgMap


  const colors = ['#a10000', '#00067d', '#997405']
  const deviceColor = {"坦克":'#a10000', "运输车":'#00067d', "装甲车":'#997405'}

  const [devices, setDevices] = useState([])
  const [selectedDevices, setSelectedDevices] = useState([])
  const selectedDevicesRef = useRef(selectedDevices)
  const [myChart, setMyChart] = useState()
  const [option, setOption] = useState()


  const [timer, setTimer] = useState(null)

  const [count, setCount] = useState(0)

  const countRef = useRef(count)

  useEffect(() => {
    selectedDevicesRef.current = selectedDevices
    countRef.current = count
  })

  useEffect(() => {
    console.log("==update selected devices===")
    setData(selectedDevices?.map((item, index) => {
      return {
        doi: item.doi,
        effect: {
          color: item.color,
          constantSpeed: 50,
          delay: 0
        },
        coords: item.coords,
      }
    }))
  }, [selectedDevices])


  const [data, setData] = useState([])

  const updateStatus = () => {

    setCount(countRef.current + 1)

    for (const index in selectedDevicesRef.current) {
      const doi = selectedDevicesRef.current[index]?.doi
      //请求服务端数据，进行更新
      // axios.get("http://127.0.0.1:8000/app/geo" + doi)
      //   .then(function (response) {
      //     setData((preData) => {
      //       if (preData == null || preData.length == 0)
      //         return []
      //       return preData.map((item, preIndex) => {
      //         if (doi === item.doi) {
      //           item.coords = response.data
      //           if (item.coords?.length > 0) {
      //             const position = item.coords.slice(countRef.current % item.coords.length, countRef.current % item.coords.length + 1)[0]
      //             item.coords = [position, [position[0] + 1, position[1] + 1]]
      //           }
      //           return item
      //         } else {
      //           return item
      //         }
      //       })
      //     })
      //   })
      //   .catch(function (error) {
      //
      //   })

      axios.get(selectedDevicesRef.current[index]?.url)
        .then(function (response) {

          console.log("===get the geo:\n" + JSON.stringify(response.data))
          if(response?.data?.rtnMsg !== "success")
            return
          setData((preData) => {
            if (preData == null || preData.length == 0)
              return []
            return preData.map((item, preIndex) => {
              if (doi === item.doi) {
                const position = JSON.parse(response?.data?.data?.location)
                item.coords = [position, [position[0] + 1, position[1] + 1]]
                return item
              } else {
                return item
              }
            })
          })
        })
        .catch(function (error) {

        })

    }
  }

  const downloadSvg = () => {

    const myChartLoc = echarts.init(document.getElementById("content"))
    setMyChart(myChartLoc)

    // axios.get("http://127.0.0.1:8000/app/devices")
    //   .then(function (response) {
    //     setDevices(response.data)
    //   })
    //   .catch(function (error) {
    //
    //   })




    axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';

    axios.defaults.headers.get['Content-Type'] ='application/json;charset=utf-8';
    axios.defaults.headers.get['Access-Control-Allow-Origin'] = '*';


    axios.get("http://127.0.0.1:8000/gdata-rest/sdk/applicationsByName/战场态势/metadata?pageNum=1&numPerPage=10&username=superadmin", {httpsAgent: { rejectUnauthorized: false}})
      .then(function (response) {
        const app = response.data?.data?.metadataPage?.list
        const fapp = app.filter(function (item){return item.status !== "FREEZE"})
        setDevices(fapp?.map((item, index) => {
          return {key:item.doi, doi: item.doi, color:deviceColor[item.metadataName],coords:[[1,1],[2,2]], name: item.metadataName, url:item.url.replace("https","http").replace("39.101.64.229","127.0.0.1:8000").replace("appSecret=02E5GYcGfAhIdvcpUjxI","sld-apikey=7dce169f637744cd811efb1b35a20fc6").replace("appkey=UYUguDKnAtLT9yNLznbd\&","")}
          })
        )
      })
      .catch(function (error) {

      })


    axios.get('http://127.0.0.1:8000/ksia-ext-plan-min.svg')
      .then(function (response) {
        svgMap = response.data
        echarts.registerMap('ksia-ext-plan', {svg: svgMap});
        const optionLoc = {
          title: {
            text: '移动路线',
            left: 'center',
            bottom: 10
          },
          tooltip: {},
          geo: {
            map: 'ksia-ext-plan',
            roam: true,
            layoutCenter: ['50%', '50%'],
            layoutSize: '100%'
          },
          series: [
            {
              name: '状态',
              type: 'lines',
              coordinateSystem: 'geo',
              geoIndex: 0,
              emphasis: {
                label: {
                  show: false
                }
              },
              polyline: true,
              lineStyle: {
                color: '#c46e54',
                width: 0
              },
              effect: {
                show: true,
                period: 50,
                color: '#a10000',
                // constantSpeed: 80,
                trailLength: 0,
                symbolSize: [12, 30],
                //小车形状
                symbol:
                  'path://M87.1667 3.8333L80.5.5h-60l-6.6667 3.3333L.5 70.5v130l10 10h80l10 -10v-130zM15.5 190.5l15 -20h40l15 20zm75 -65l-15 5v35l15 15zm-80 0l15 5v35l-15 15zm65 0l15 -5v-40l-15 20zm-50 0l-15 -5v-40l15 20zm 65,-55 -15,25 c -15,-5 -35,-5 -50,0 l -15,-25 c 25,-15 55,-15 80,0 z'
              },
              z: 100,
              data: data
            }
          ]
        };
        setOption(optionLoc)
        myChartLoc.setOption(optionLoc);
      })
      .catch(function (error) {

      })
  }

  useEffect(() => {
    downloadSvg()
    setTimer(setInterval(() => {
      updateStatus()
    }, 3000))

    //相当于componentWillUnmount
    return () => {
      timer && clearInterval(timer)
    }

  }, [])

  useEffect(() => {
    console.log("====update the status===\n" + JSON.stringify(data))
    myChart?.setOption({
      series: [
        {
          name: '状态',
          data: data
        }]
    });
  }, [data])


  const columns = [
    {
      title: '标识',
      width: 40,
      dataIndex: 'doi',
      ellipsis: true,
      fixed: 'left',
      render: (_) => <a>{_}</a>,
    },
    {
      title: '名称',
      width: 40,
      dataIndex: 'name',
      fixed: 'center',
      search: false,
    },
    {
      title: '访问地址',
      width: 80,
      dataIndex: 'url',
      align: 'center',
      ellipsis: true,
      search: false,
    },
  ]

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    console.log(selectedRows)
    setSelectedDevices(selectedRows)
  }


  return (
    <PageContainer
    >
      <ProCard style={{"margin-bottom": "20px"}}>
        <ProCard title={"可访问设备列表"} colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <ProTable
            columns={columns}
            rowSelection={{
              // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
              // 注释该行则默认不显示下拉选项
              selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              onChange: onSelectChange
            }}

            tableAlertRender={({selectedRowKeys, selectedRows, onCleanSelected}) => (
              <Space size={24}>
                <span>
                  已接入 {selectedRowKeys.length} 项
                  <a style={{marginLeft: 8}} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            )}
            tableAlertOptionRender={() => {
              return (
                <Space size={16}>

                </Space>
              );
            }}
            dataSource={devices}
            scroll={{x: 300}}
            options={false}
            search={false}
            rowKey="key"
            headerTitle="批量操作"
            toolBarRender={() => [<Button primary onClick={() => {
            }}>刷新</Button>]}
          />
        </ProCard>
        <ProCard title={"现场态势图"} colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <div id={"content"} style={{"height": "700px", "width": "1000px"}}></div>
        </ProCard>
      </ProCard>

    </PageContainer>
  );
};
